/*    file: TimeChecker.cpp
 *    desc:
 * 
 * created: 2016-06-30
 *  author: chuanjiang.zh@qq.com
 * company: 
 */

#include "TimeChecker.h"
#include "CLog.h"

namespace util
{


TimeChecker::TimeChecker():
	m_clockGap(DEFAULT_GAP),
	m_ptsGap(DEFAULT_GAP)
{
}

void TimeChecker::reset()
{
    m_start.reset();
    m_cur.reset();
    m_count = 0;
}

bool TimeChecker::input(int64_t clk, int64_t pts)
{
	bool isNormal = true;
    if (!m_cur.isSet())
    {
        m_start.reset(clk, pts);
        m_cur = m_start;
        m_count = 1;
    }
    else
    {
		int64_t duration = clk - m_cur.m_clock;
		int64_t offset = pts - m_cur.m_pts;

		if (duration > m_clockGap)
		{
			isNormal = false;
			CLog::warning("clock gap. last: %lld, cur: %lld, duration: %lld\n", m_cur.m_clock, clk, duration);
		}

		if (offset < 0)
		{
			isNormal = false;
			CLog::warning("pts decreased. last: %lld, cur: %lld, offset: %lld\n", m_cur.m_pts, pts, offset);
		}
		else if (offset > m_ptsGap)
		{
			isNormal = false;
			CLog::warning("pts gap. last: %lld, cur: %lld, offset: %lld\n", m_cur.m_pts, pts, offset);
		}

        m_cur.reset(clk, pts);
        m_count ++;
    }
	return isNormal;
}

void TimeChecker::setClockGap(int64_t gap)
{
	m_clockGap = gap;
}

void TimeChecker::setPtsGap(int64_t gap)
{
	m_ptsGap = gap;
}

int64_t TimeChecker::getClockDuration() const
{
    return m_cur.m_clock - m_start.m_clock;
}

int64_t TimeChecker::getPtsDuration() const
{
    return m_cur.m_pts - m_start.m_pts;
}

int64_t TimeChecker::getCount() const
{
    return m_count;
}


}